package controllers

import (
	"github.com/astaxie/beego"
	"html/template"
	"ktvserver/webserver/view"
	//"log"
	"bytes"
	"fmt"
	"io/ioutil"
	"ktvserver/ktvutil"
	"time"
)

var (
	temp *template.Template
)

type BaseController struct {
	beego.Controller
}

// 重载渲染函数
func (c *BaseController) Render() error {
	//c.Ctx.WriteString("template=")
	//c.Ctx.WriteString(c.TplNames)
	//log.Printf("template=%s", c.TplNames)
	// 记录模板的名称
	c.Data["tpl"] = c.TplNames

	if len(c.TplNames) > 0 {
		newbytes := bytes.NewBufferString("")
		temp.ExecuteTemplate(newbytes, c.TplNames, c.Data)
		tplcontent, _ := ioutil.ReadAll(newbytes)
		c.Ctx.Output.Header("Content-Type", "text/html; charset=utf-8")
		c.Ctx.Output.Body(tplcontent)
	}

	return nil
}

type UserController struct {
	BaseController
}

// 检查是否已经登录
func (c *UserController) Prepare() {

	// 检查是否已经登录
	if c.GetSession(SESSION_KEY_ISLOGIN) != "true" {
		to_url := "/login?next=" + c.Ctx.Input.Uri()
		//log.Printf("next=%s", next)
		c.Redirect(to_url, 302)
		return
	}

	c.Data["islogin"] = 1

}

// 模板函数
var funcMaps = template.FuncMap{
	"html": func(text string) template.HTML {
		return template.HTML(text)
	},
	"formatdate": func(t time.Time) string {
		// 格式化日期
		return t.Format(time.RFC822)
	},
	"formattime": func(sec int64) string {
		// 格式化时间
		t := time.Unix(sec, 0)
		now := time.Now()
		duration := now.Sub(t)
		if duration.Seconds() < 60 {
			return fmt.Sprintf("刚刚")
		} else if duration.Minutes() < 60 {
			return fmt.Sprintf("%.0f 分钟前", duration.Minutes())
		} else if duration.Hours() < 24 {
			return fmt.Sprintf("%.0f 小时前", duration.Hours())
		}

		return t.Format("01-02 15:04")
	},
	"formatdatetime": func(t time.Time) string {
		// 格式化时间成 2006-01-02 15:04:05
		return t.Format("2006-01-02 15:04:05")
	},
	"noescape": func(s string) template.HTML {
		return template.HTML(s)
	},
	"transfer": func(length int64) string {
		if length < 1024 {
			// B
			return fmt.Sprintf("%d B", length)

		} else if length < 1024*1024 {
			// KB
			return fmt.Sprintf("%.2f KB", float64(length)/1024)

		} else if length < 1024*1024*1024 {
			// MB
			return fmt.Sprintf("%.2f MB", float64(length)/(1024*1024))
		} else {
			// GB
			return fmt.Sprintf("%.2f GB", float64(length)/(1024*1024*1024))
		}

	},

	"getsongname": func(songnum uint32) string {
		return ktvutil.KtvGetSongNameByNum(songnum)
	},
	"inc": func(number int) int {
		return number + 1
	},
}

func init() {

	temp = template.New("foo").Funcs(funcMaps)
	allTemplates := view.GetTemplates()

	for _, t := range allTemplates {
		temp.Parse(t)
	}

}
